<template>
    <el-dialog title=" " :visible.sync="faceDialogVisible" top="30px" width="1080px" append-to-body>
        <el-form :model="form.model" :rules="form.rules" ref="form">
            <el-row :gutter="12">
                <el-col :span="14">
                    <div class="cut-wrapper" :class="{ismove: isMove}" >
                        <!-- <img src="@/assets/login/bg.jpg " :style="imgPosition" @load="imgOnload" ref="img" -->
                        <img :src="imgsrc" :style="imgPosition" @load="imgOnload" ref="img"
                        @mousedown.prevent="mouseDown"
                        @mouseup.prevent="mouseUp"
                        @mousemove.prevent="mouseMove"
                        @mouseleave.prevent="mouseLeave">
                        <el-button v-if="!imgsrc" @click="$refs.file.click()">添加图片</el-button>
                    </div>
                    <canvas v-if="imgsrc!=config.avatar" width="480" height="640" ref="canvas" style="width:480px; height: 640px"></canvas>
                    <!-- <img :src="imgurl" style="verticle-align:top;"/> -->

                    <input type="file" name="" ref="file" @change="fileChange" style="display:none">
                </el-col>
                <el-col :span="10">
                    <el-form-item label="有效时间" prop="datetime">
                        <el-date-picker style="width:100%" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss"
                            v-model="form.model.datetime"></el-date-picker>
                    </el-form-item>
                    <el-form-item label="备注" prop="remark">
                        <el-input type="textarea" :rows="6" v-model="form.model.remark"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-button @click="$refs.file.click()">上传新头像</el-button>
            <el-button @click="faceDialogVisible=false">取消</el-button>
            <el-button @click="handleCut" v-if="imgsrc!=config.avatar && imgsrc">确定</el-button>
        </template>
    </el-dialog>
</template>
<script>

export default {
    props: {
        config: {
            type: Object,
            default() {
                return {}
            }
        }
    },
    data() {
        return {
            form: {
                model: {
                    datetime: null,
                    remark: ''  
                },
                rules: {
                    datetime: [{trigger: 'blur', required: true, message: '请选择有效时间'}],
                    remark: [{trigger: 'blur', required: true, message: '请填写备注'}],
                }
            },

            faceDialogVisible: true,
            isMove: false,
            naturalRix: 1,
            naturalWidth: 0,
            naturalHeight: 0,
            cw: 480, ch: 640, needRix: 480/640,
            // cw: 400, ch: 200, needRix: 400/200,
            marginLeft: 0,
            marginTop: 0,
            preX: 0,
            preY: 0,
            isWidthFull: false,
            imgurl: '',
            imgsrc: ''
        }
    },
    watch: {
        faceDialogVisible: {
            immediate: true,
            handler() {
                this.$emit('close', this.faceDialogVisible)
            }
        }
    },
    computed: {
        imgPosition() {
            return { marginLeft: this.marginLeft + 'px', marginTop: this.marginTop + 'px' }
        }
    },
    created() {
        if( !this.config.avatar ) return false;
        this.imgsrc = this.config.avatar;
    },
    methods: {
        fileChange() {
            var input = this.$refs.file;
            var file = input.files[ 0 ];
            var sufix = file.name.substring(file.name.lastIndexOf('.') + 1);
            input.value='';

            if( !/jpg|jpeg|png/ig.test(sufix) ) return this.$message.error('请上传jpg、jpeg、png类型的文件');

            var fileReader = new FileReader;
            fileReader.onload = ({target}) => {
                this.imgsrc = target.result;
                fileReader.onload = null;
                fileReader = null; 
            };
            fileReader.readAsDataURL(file);
        },
        mouseDown(ev) {
            this.isMove = true;
            this.preX = ev.layerX;
            this.preY = ev.layerY;
        },
        mouseMove(ev) {
            var rightRect = this.naturalWidth/(this.naturalHeight/this.ch) - this.cw;
            var bottomRect = this.naturalHeight/(this.naturalWidth/this.cw) - this.ch;

            if( !this.isMove ) return false;
            var { layerX, layerY } = ev;    // 容器相对位置

            var newX = layerX - this.preX, newY = layerY - this.preY;
            if( this.isWidthFull ) {    // 如果宽度撑满，则以高度上下移动
                this.marginTop += newY;
                if( this.marginTop >= 0 ) this.marginTop = 0;
                if( Math.abs(this.marginTop) >= bottomRect ) this.marginTop = -bottomRect;
            } else {    // 只处理左右移动
                this.marginLeft += newX;
                if( this.marginLeft >= 0 ) this.marginLeft = 0;
                if( Math.abs(this.marginLeft) >= rightRect ) this.marginLeft = -rightRect;
            }
            this.preX = layerX;
            this.preY = layerY;

            this.renderImg();
        },
        mouseLeave() {
            this.isMove = false;
        },
        mouseUp() { 
            this.isMove = false;
        },
        handleCut() {
            this.$refs.form.validate(valid=>{
                if( !valid )  return false;
                var canvas = this.$refs.canvas;
                this.imgurl = canvas.toDataURL();
                this.$emit('success', {
                    src: this.imgurl,
                    ...this.form.model
                });
            });
        },
        renderImg() {
            var img = this.$refs.img;
            var canvas = this.$refs.canvas;
            var ctx = canvas.getContext('2d');
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            if( this.isWidthFull ) {
                var scale = this.naturalWidth / this.cw;
                var scaleHeight = this.naturalHeight / scale;
                var startY = (Math.abs(this.marginTop)*this.naturalHeight)/scaleHeight;
                ctx.drawImage(img, 0, startY, this.naturalWidth, this.ch*scale, 0, 0, this.cw, this.ch);

            } else {    // height: 100%
                var scale = this.naturalHeight / this.ch;
                var scaleWidth = this.naturalWidth / scale;
                var startX = (Math.abs(this.marginLeft)*this.naturalWidth)/scaleWidth;
                ctx.drawImage(img, startX, 0, this.cw*scale, this.naturalHeight, 0, 0, this.cw, this.ch);
            }
        },
        imgOnload() {
            this.marginLeft = 0;
            this.marginTop = 0;
            this.preX = 0;
            this.preY = 0;
            this.isWidthFull = false;

            var img = this.$refs.img;
            this.naturalWidth = img.naturalWidth;
            this.naturalHeight = img.naturalHeight;
            this.naturalRix = this.naturalWidth / this.naturalHeight;
            var style = {};
            if( this.naturalRix > this.needRix ) {  // 宽度较大
                var rid = this.naturalHeight / this.ch;
                var width = this.naturalWidth / rid;
                this.marginLeft = -(width - this.cw) / 2;
                var style = {
                    height: '100%',
                    width: 'auto'
                };
                
            } else {
                var rid = this.naturalWidth / this.cw;
                var height = this.naturalHeight / rid;
                this.marginTop = -(height - this.ch) / 2;
                this.isWidthFull = true;
                var style = {
                    width: '100%',
                    height: 'auto'
                };
            }
            Object.keys(style).forEach(key=>{
                img.style[key] = style[key];
            });
            this.$nextTick(()=>{
                this.renderImg();
            });
        },
    }
}
</script>
<style lang="scss" scoped>
.cut-wrapper {
    position: relative;
    margin: 0 auto;
    width: 480px; height: 640px;
    background: #eee;
    overflow: hidden;
    &.ismove { cursor: move; }
    cursor: move;
    & +canvas {
        position: absolute;
        left: 0; top: 0;
        z-index: -1;
        opacity: 0;
    }
    .el-button {
        position: absolute;
        left: 50%; top: 50%;
        transform: translateX(-50%) translateY(-50%);
    }
}
</style>